<template>
    <div>
    <div class="box">
    <el-form size="mini" :model="goodsForm" status-icon :rules="goodsRules" ref="goodsForm" label-width="100px" class="goodsForm">
      <el-form-item label="id" prop="id">
        <el-input type="text" v-model="goodsForm.id"></el-input>
      </el-form-item>
      <el-form-item label="商品介绍" prop="intorduce">
        <el-input type="text" v-model="goodsForm.intorduce"></el-input>
      </el-form-item>
      <el-form-item label="商品图" prop="picture" class="picture">
        <input type="file" name="picture" accept="image/*" @change="getPicture($event)" ref="picture">
        <img v-if="pictureUrl" id="picture" :src=pictureUrl alt="" width="60px" height="60px">
      </el-form-item>
      <el-form-item label="商品详情图" prop="morePicture" class="morePicture">
        <input type="file" name="morePicture" multiple accept="image/*" @change="getMorePicture($event)" ref="morePicture">
        <div v-for="(item,index) in morePictureUrl" :key="index">
            <img v-if="morePictureUrl.length" id="morePicture" :src=item alt="" width="60px" height="60px">
        </div>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input type="text" v-model="goodsForm.price"></el-input>
      </el-form-item>
      <el-form-item label="类别" prop="type">
        <el-input type="text" v-model="goodsForm.type" placeholder="洗面奶|水乳|面霜|精华"></el-input>
      </el-form-item>
      <el-form-item label="适用年龄" prop="age">
        <el-input v-model.number="goodsForm.age" placeholder="18|24|30|31"></el-input>
      </el-form-item>      
      <el-form-item>
        <el-button type="success" @click="submitForm('goodsForm')">添加</el-button>
        <el-button @click="resetForm('goodsForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  </div>
</template>
<script>
export default {
  name: "goodsAdd",
  data() {     
    return {
      // 前端页面展示的图片路径
      pictureUrl:'',
      morePictureUrl:[],
      // 传递给后端的商品信息
      goodsForm: {
          id:'',
          intorduce:'',
          pictureUrl:'',
          morePictureUrl:[],
          price:'',
          type:'',
          age:''
        },
        goodsRules: {
          id: [
            { required: true, message: '请输入商品id', trigger: 'blur' }
          ],
          intorduce: [
            { required: true, message: '请输入商品介绍', trigger: 'blur'  }
          ],
          pictureUrl: [
            {  required: true, message: '请上传商品图片', trigger: 'blur'  }
          ],
          morePictureUrl: [
            {  required: true, message: '请上传商品详情图', trigger: 'blur'  }
          ],
          price: [
            {  required: true, message: '请输入商品价格', trigger: 'blur'  }
          ],
          type: [
          {  required: true, message: '请输入商品类型', trigger: 'blur'  }
          ],
          age: [
          {  required: true, message: '请输入适应年龄', trigger: 'blur'  }
          ]
        }
      
    };
  },
  methods: {
    // 上传商品图 得到base64
    getPicture(event) {
        let that  =this;
        let file = event.target.files[0];
        //   event.target.files[0];这个东西就是图片
        // FileReader是H5提供的一个处理文件的API 其读取文件后不会返回FileReader本身而是存储在result中
        let reader = new FileReader();
        // readAsDataUrl(file)读取文件并将文件以数据URL的形式保存在result属性中
        reader.readAsDataURL(file);
        let dataURL;
        //onloadend数据读取完成时触发，无论成功或失败
        reader.onloadend = function () {
          // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
          dataURL = reader.result;
          // 前端展示图片路径
          that.pictureUrl=dataURL;
          // 将base64图片转换为blob再转为url(http) 传给后端
          // 得到file对象that.dataURLtoFile(dataURL); 得到url(输出为：blob:http://localhost:8080/6df3bb1e-c33b-4c6d-bf34-820c1085e61a)
          let url = (window.webkitURL.createObjectURL(that.dataURLtoFile(dataURL))||window.URL.createObjectURL(that.dataURLtoFile(dataURL))).substring(5)
          that.goodsForm.pictureUrl=url
          console.log(url);
        }
    },
    // 上传商品详情图 得到base64
    getMorePicture(event) {
        let that  =this;
        for(let i=0;i< event.target.files.length;i++){
            let reader = new FileReader();
            // readAsDataUrl(file)读取文件并将文件以数据URL的形式保存在result属性中
            reader.readAsDataURL(event.target.files[i]);
            let dataURL;
            reader.onloadend = function () {
              dataURL = reader.result;
              // 前端展示商品详情图
              that.morePictureUrl.push(dataURL)
              // 将base64图片转换为blob再转为url(http) 传给后端
              // 得到file对象that.dataURLtoFile(dataURL); 得到url
              that.goodsForm.morePictureUrl.push((window.webkitURL.createObjectURL(that.dataURLtoFile(dataURL))||window.URL.createObjectURL(that.dataURLtoFile(dataURL))).substring(5))
            }
        }
     },
    // 提交商品信息
      submitForm(formName) {
        const {id,intorduce,pictureUrl,morePictureUrl,price,type,age}=this.goodsForm
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$store.dispatch('addGoods',{id,intorduce,pictureUrl,morePictureUrl,price,type,age})
            alert('添加成功')
          } else {
            alert('添加失败');
            return false;
          }
        });
      },
    //   重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      // base64转url
      dataURLtoFile(url,filename="file") {
        // base64转blob
        var arr = url.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];
        var suffix = mime.split("/")[1];
        var bstr = atob(arr[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        // return new Blob([u8arr], {type: mime});
        // blob转url
        return new File([u8arr],`${filename}.${suffix}`,{
          type:mime
        })
      }
    }
};
</script>

<style lang='less' scoped>
    .box{
        .goodsForm{
            .picture{
                input{
                    width: 170px;
                }
                img{
                }
            }
            .morePicture{
                input{
                    width: 170px;
                }
                div{
                    display: inline;
                    img{
                    }
                }
            }
        }
    }
</style>